/**
 * 公共请求方法
 */
import Jsencrypt from 'wxmp-rsa';
import env from '../config/env';
import apis from '../config/api/index';
import message from './message';
import {
	OBSupload
} from './upload';
import requestCode from '../config/code';

/**
 * 获取短信验证码
 * @param {Function} phoneNumber 手机号码
 * @param {Function} prefunction 前置函数，在发起请求前调用
 * @param {Function} callback 回调函数，在发起请求后调用
 * @param {Function} errFunction 错误函数，在请求错误时调用
 * @param {Boolean} hasValid 是否需要验证当前手机和当前绑定的手机号一致
 */
export const getPhoneCode = (phoneNumber, prefunction, callback, errFunction, hasValid = false) => {
	if (prefunction) {
		prefunction();
	}
	if (hasValid) {
		apis.mine
			.getPhoneVerificationCode({
				phoneNumber
			})
			.then(
				(res) => {
					if (callback) {
						callback(res);
					}
				},
				(err) => {
					if (errFunction) {
						errFunction(err);
					}
				}
			);
	} else {
		apis.base
			.getPhoneVerification({
				phoneNumber
			})
			.then(
				(res) => {
					if (callback) {
						callback(res);
					}
				},
				(err) => {
					if (errFunction) {
						errFunction(err);
					}
				}
			);
	}
};

/**
 * 获取华为云配置
 */
export const getOBSConfig = () => {
	apis.base.getObs().then((res) => {
		if (!res.data) {
			return;
		}
		const jsencrypt = new Jsencrypt();
		jsencrypt.setPrivateKey(env.RSA);
		console.log('加载华为云配置成功');
		uni.setStorageSync('cisdiHwConfig', JSON.parse(jsencrypt.decryptLong(res.data)));
	});
};

/**
 * 处理头像地址
 */
export function handleAvatarUrl(avatarUrl) {
	if (avatarUrl.indexOf('?') > -1 && avatarUrl.indexOf('//') > -1 && avatarUrl.indexOf('/') > -1) {
		avatarUrl = avatarUrl.split('?')[0].split('//')[1].split('/')[1];
	} else {
		return '';
	}
	return avatarUrl;
}

/**
 * 判断两个头像地址是否一样
 * @param {头像A} avatarA
 * @param {头像B} avatarB
 */

export const isSameAvatar = (avatarA, avatarB) => {
	return handleAvatarUrl(avatarA) == handleAvatarUrl(avatarB);
};
/**
 * 防抖函数
 */
export const debounce = (function() {
	let timer = 0;
	return function(fn, delay = 300) {
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(() => {
			fn();
		}, delay);
	};
})();

/**
 *
 * @param {数字} num
 * 转化为大写数字
 */
export const toChinesNum = (num) => {
	let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
	let unit = ['', '十', '百', '千', '万'];
	num = parseInt(num);
	let overWan = Math.floor(num / 10000);
	let getWan = (temp) => {
		let strArr = temp.toString().split('').reverse();
		let newNum = '';
		for (var i = 0; i < strArr.length; i++) {
			newNum = (i == 0 && strArr[i] == 0 ? '' : i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? '' :
				changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i])) + newNum;
		}
		if (strArr.length == 2 && strArr[1] == 1) {
			let arr = newNum.split('');
			arr.splice(0, 1);
			newNum = arr.join('');
		}
		return newNum;
	};
	let noWan = num % 10000;
	if (noWan.toString().length < 4) {
		noWan = '0' + noWan;
	}
	return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num);
};
export const uploadFile = (extension = ['pdf'], fn, limit = 50) => {
	wx.chooseMessageFile({
		count: 1,
		type: 'file',
		extension,
		success(res) {
			const tempFilePaths = res.tempFiles;
			let fileType = tempFilePaths[0].path.split('.')[1];
			fileType = fileType.toLocaleLowerCase();
			let flag = false;
			for (let item of extension) {
				if (item == fileType) {
					flag = true;
					break;
				}
			}
			if (!flag) {
				message.toast('文件格式不符合');
				if (fn) {
					fn({
						code: -1,
						url: ''
					});
				}
				return;
			}
			if (tempFilePaths[0].size / 1048576 > limit) {
				message.toast(`上传文件大小不能超过${limit}兆`);
				if (fn) {
					fn({
						code: -1,
						url: ''
					});
				}
				return;
			}
			OBSupload(tempFilePaths[0].path, (data) => {
				if (fn) {
					fn(data);
				}
				uni.hideLoading();
			});
		},
		fail: (err) => {
			console.log(err);
			if (fn) {
				fn({
					code: -1,
					url: ''
				});
			}
		}
	});
};

/**
 * 为了审核
 */
export const hiddenAuth = (app) => {
	if (app.globalData.currentProject && app.globalData.currentProject.projectName) {
		return true;
	}
	return false;
};

/**
 * 新增人员时统一校验
 */
export const addRosterCheck = (res = {}, submitFn, cancelFn, otherFn) => {
	if (res.code === requestCode.ADD_ROSTER_TIP) {
		//人员预警提示
		uni.showModal({
			title: '温馨提示',
			content: res.msg,
			confirmText: '确认录入',
			complete: (action) => {
				if (action.confirm) {
					if (submitFn) {
						submitFn();
					}
				}
				if (action.cancel) {
					if (cancelFn) {
						cancelFn();
					}
				}
			}
		});
		return;
	} else if (res.code === requestCode.ADD_ROSTER_FORBID) {
		uni.showModal({
			title: '温馨提示',
			content: res.msg,
			showCancel: false,
			complete: (action) => {
				if (action.confirm) {
					if (cancelFn) {
						cancelFn();
					}
				}
			}
		});
		return;
	} else {
		if (otherFn) {
			otherFn();
		}
	}
};
/**
 * 统一处理后端返回图片显示问题
 */
export const imgShow = url => {
	let splitText = '.obs.cn-southwest-6034.chongqingxc02.huaweigovcloud.com/';
	if (url && url.indexOf(splitText) > -1) {
		let hwConfig = uni.getStorageSync('cisdiHwConfig');
		return `${env.uploadImgUrl}/${hwConfig.bucket}/${url.split(splitText)[1]}`;
	}
	return url;
};